package com.zhangkunhao.notes.service;


import com.zhangkunhao.notes.dao.QuestionDao;

import com.zhangkunhao.notes.entity.Do.Question;

import com.zhangkunhao.notes.entity.bo.LegalWordsDetector;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.service.impl.QuestionService;
import com.zhangkunhao.notes.utils.IfValidInputUtil;
import com.zhangkunhao.notes.utils.IllegalWordsDetectorUtils;

import java.sql.SQLException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 问题接口的实现类
 *
 * @author 20642
 */
public class QuestionServiceImpl implements QuestionService {

    @Override
    public List<Question> selectAll() {
        return QuestionDao.getInstance().findAll();
    }

    @Override
    public void insert(Question question) throws Exception {
        QuestionDao.getInstance().insert(question);
    }

    @Override
    public int delete(int id) throws SQLException {
        return QuestionDao.getInstance().delete(id);
    }

    @Override
    public int update(Question question, String... params) throws Exception {
        return QuestionDao.getInstance().update(question);
    }

    /**
     * 发布问题
     *
     * @param question：
     * @return Message<Question>
     * @throws Exception：
     */
    public Message<Question> askQuestion(Question question) throws Exception {
        System.out.println("问题对象 " + question);
        //初始化
        Message<Question> askQuestionMessage = new Message<>(null, "发布问题失败", 0);


        //判断
        if (question == null) {
            askQuestionMessage.setResult("当前问题为空");
            return askQuestionMessage;
        } else {
            if (!(IfValidInputUtil.ifValidValue(question.getTitle()))) {
                askQuestionMessage.setResult("当前问题标题为空");
                return askQuestionMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(question.getTitle()))) {
                askQuestionMessage.setResult("当前问题标题出现空格");
                return askQuestionMessage;
            }
            if (!(IfValidInputUtil.ifValidValue(question.getContent()))) {
                askQuestionMessage.setResult("当前问题内容为空");
                return askQuestionMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(question.getContent()))) {
                askQuestionMessage.setResult("当前问题内容出现空格");
                return askQuestionMessage;
            }
            if (!(IfValidInputUtil.ifValidValue(question.getClassification()))) {
                askQuestionMessage.setResult("当前问题分类为空");
                return askQuestionMessage;
            }
        }

        //调用工具类进行敏感词汇，如诋毁党、⾊情等信息检测
        LegalWordsDetector contentCheck = IllegalWordsDetectorUtils.isLegalWords(question.getContent());
        if (!contentCheck.isIsLegal()) {
            askQuestionMessage.setResult("问题内容" + contentCheck.getMsg());
            return askQuestionMessage;
        }
        LegalWordsDetector titleCheck = IllegalWordsDetectorUtils.isLegalWords(question.getTitle());
        if (!titleCheck.isIsLegal()) {
            askQuestionMessage.setResult("问题标题" + titleCheck.getMsg());
            return askQuestionMessage;
        }

//        //查询，判断权限
//        PermissionBlacklistServiceImpl blacklistService = new PermissionBlacklistServiceImpl();
//        List<PermissionBlacklist> permissionBlacklistList = blacklistService.selectAll().stream()
//                .filter(permissionBlacklist -> permissionBlacklist.getBanUserId().equals(question.getPublishUserId())
//                        && permissionBlacklist.getBanPermissionName().equals("发布问题")).collect(Collectors.toList());
//        //判断校验
//        if (!permissionBlacklistList.isEmpty()) {
//            System.out.println("我进入发布问题的黑名单了");
//            for (PermissionBlacklist permissionBlacklist : permissionBlacklistList) {
//                //判断是否封禁时间已经到了
//                if (permissionBlacklist.getOpenDate().compareTo(new Timestamp(System.currentTimeMillis())) >= 0) {
//                    //返回数据
//                    askQuestionMessage.setResult("你发布问题的权限已经被管理员封禁了，并且没有到解封日期");
//                    return askQuestionMessage;
//                }
//            }
//        }

        //调用dao
        this.insert(question);

        List<Question> questionList = this.selectAll();

        for (Question question2 : questionList) {
            if (question2.getTitle().equals(question.getTitle()) && question2.getContent().equals(question.getContent())
                    && question2.getClassification().equals(question.getClassification())
                    && question2.getPublishUserId().equals(question.getPublishUserId())) {
                System.out.println("askQuestionSuccess");
                askQuestionMessage.setResult("问题发布成功,已刷新当前页面");
                askQuestionMessage.setStatus(1);
                askQuestionMessage.setT(question2);
                break;
            }
        }
        return askQuestionMessage;
    }

    /**
     * 点赞问题
     *
     * @param question：
     * @return Message<Question>
     * @throws Exception：
     */
    public Message<Question> thumpsUp(Question question) throws Exception {
        System.out.println("点赞的问题对象 " + question);
        //初始化
        Message<Question> thumpsUpMessage = new Message<>(null, "点赞失败", 0);

        //校验
        if (question == null) {
            thumpsUpMessage.setResult("当前问题为空");
            return thumpsUpMessage;
        }

        //修改
        question.setLikeCount(question.getLikeCount() + 1);

        //调用dao
        int update = this.update(question);

        if (update > 0) {
            System.out.println("thumpsUpQuestionSuccess");
            thumpsUpMessage.setResult("问题点赞成功,已刷新当前页面");
            thumpsUpMessage.setStatus(1);
            thumpsUpMessage.setT(question);
        } else {
            thumpsUpMessage.setResult("问题点赞失败,未刷新当前页面");
        }
        return thumpsUpMessage;
    }

    /**
     * 举报问题
     *
     * @param reportQuestionId：
     * @param reportQuestionReason：
     * @return Message<Question>
     * @throws Exception：
     */
    public Message<Question> reportQuestion(int reportQuestionId, String reportQuestionReason) throws Exception {
        //查找数据
        Question reportQuestion = this.selectAll().stream()
                .filter(question1 -> question1.getId().equals(reportQuestionId))
                .collect(Collectors.toList()).get(0);

        //封装返回对象
        Message<Question> reportQuestionMessage = new Message<>(null, "举报失败，请重新尝试", 0);

        //校验
        if (reportQuestion == null) {
            reportQuestionMessage.setResult("当前被举报的问题为空");
            return reportQuestionMessage;
        } else if (!(IfValidInputUtil.ifValidValue(reportQuestionReason))) {
            reportQuestionMessage.setResult("问题的举报理由为空，请重新填写");
            return reportQuestionMessage;
        }

        //修改
        reportQuestion.setReportIllegalReason(reportQuestionReason);
        reportQuestion.setReportStatus(0);

        System.out.println("被举报的问题对象 " + reportQuestion);

        //调用dao
        int update = this.update(reportQuestion);

        if (update > 0) {
            System.out.println("reportQuestionSuccess");
            reportQuestionMessage.setResult("问题举报成功,已刷新当前页面");
            reportQuestionMessage.setStatus(1);
            reportQuestionMessage.setT(reportQuestion);
        } else {
            reportQuestionMessage.setResult("问题举报失败,未刷新当前页面");
        }
        return reportQuestionMessage;
    }

    /**
     * 管理员驳回上传问题的审核
     *
     * @param rejectQuestionId：
     * @param rejectReason：
     * @return Message<Question>
     * @throws Exception：
     */
    public Message<Question> sendRejectQuestion(int rejectQuestionId, String rejectReason) throws Exception {
        //初始化
        Message<Question> rejectQuestion = new Message<>(null, "驳回问题审核失败，请重新尝试", 0);

        //查找数据
        Question question = this.selectAll().stream()
                .filter(question1 -> question1.getId().equals(rejectQuestionId)).collect(Collectors.toList()).get(0);
        //校验
        if (question == null) {
            rejectQuestion.setResult("当前被驳回审核的问题为空");
            return rejectQuestion;
        } else if (!(IfValidInputUtil.ifValidValue(rejectReason))) {
            rejectQuestion.setResult("问题上传审核不通过的理由为空，请重新填写");
            return rejectQuestion;
        } else if ("审核中".equals(rejectReason)) {
            rejectQuestion.setResult("审核不通过的理由不合要求，请重新填写");
            return rejectQuestion;
        }

        //驳回审核理由进行敏感字符校验
        LegalWordsDetector legalWords = IllegalWordsDetectorUtils.isLegalWords(rejectReason);
        if (!legalWords.isIsLegal()) {
            rejectQuestion.setResult("驳回理由" + legalWords.getMsg());
            return rejectQuestion;
        }

        //修改
        question.setCheckIllegalReason(rejectReason);

        System.out.println("审核不通过的问题对象 " + question);

        //调用dao
        int update = this.update(question);

        if (update > 0) {
            System.out.println("sendRejectQuestionSuccess");
            rejectQuestion.setResult("问题驳回成功,已刷新当前页面");
            rejectQuestion.setStatus(1);
            rejectQuestion.setT(question);
        } else {
            rejectQuestion.setResult("问题驳回失败,未刷新当前页面");
        }
        return rejectQuestion;
    }

    /**
     * 管理员同意发布问题的审核
     *
     * @param agreedQuestionId:
     * @return Message<Question>
     * @throws Exception:
     */
    public Message<Question> agreedPublishQuestion(int agreedQuestionId) throws Exception {
        //查找数据
        Question agreedQuestion = this.selectAll().stream()
                .filter(question -> question.getId().equals(agreedQuestionId))
                .collect(Collectors.toList()).get(0);
        //修改
        agreedQuestion.setCheckStatus(1);
        agreedQuestion.setCheckIllegalReason("无");

        System.out.println("审核通过的问题对象 " + agreedQuestion);

        //初始化
        Message<Question> questionMessage = new Message<>(null, "审核问题通过失败，请重新尝试", 0);

        //调用dao
        int update = this.update(agreedQuestion);

        if (update > 0) {
            System.out.println("agreedPublishQuestionSuccess");
            questionMessage.setResult("问题审核成功,已刷新当前页面");
            questionMessage.setStatus(1);
            questionMessage.setT(agreedQuestion);
        } else {
            questionMessage.setResult("问题审核失败,未刷新当前页面");
        }
        return questionMessage;
    }

    /**
     * 管理员同意问题的举报
     *
     * @param agreedReportQuestionId：
     * @return Message<Question>
     * @throws Exception：
     */
    public Message<Question> agreedReportQuestion(int agreedReportQuestionId) throws Exception {
        //查找数据
        Question agreedReportQuestion = this.selectAll().stream()
                .filter(question -> question.getId().equals(agreedReportQuestionId))
                .collect(Collectors.toList()).get(0);
        //初始化
        Message<Question> questionMessage = new Message<>(null, "审核被举报的问题失败，请重新尝试", 0);

        //校验
        if (agreedReportQuestion == null) {
            questionMessage.setResult("当前审核的举报问题为空");
            return questionMessage;
        }

        //修改 :-1表示管理员通过举报审核，1表示不通过举报审核，0表示仍未审核
        agreedReportQuestion.setReportStatus(-1);

        System.out.println("审核的举报问题为 " + agreedReportQuestion);

        //调用dao
        int update = this.update(agreedReportQuestion);

        if (update > 0) {
            System.out.println("agreedReportQuestionSuccess");
            questionMessage.setResult("审核成功,已刷新当前页面");
            questionMessage.setStatus(1);
            questionMessage.setT(agreedReportQuestion);
        } else {
            questionMessage.setResult("审核失败,未刷新当前页面");
        }
        return questionMessage;
    }

    /**
     * 管理员不同意问题的举报
     *
     * @param disagreedReportQuestionId：
     * @return Message<Question>
     * @throws Exception：
     */
    public Message<Question> disagreedReportQuestion(int disagreedReportQuestionId) throws Exception {
        //查找数据
        Question normalQuestion = this.selectAll().stream()
                .filter(question -> question.getId().equals(disagreedReportQuestionId))
                .collect(Collectors.toList()).get(0);
        //初始化
        Message<Question> questionMessage = new Message<>(null, "审核被举报的问题失败，请重新尝试", 0);

        //校验
        if (normalQuestion == null) {
            questionMessage.setResult("当前审核的举报问题为空");
            return questionMessage;
        }

        //修改 :-1表示管理员通过举报审核，1表示不通过举报审核，即该问题是正常的，0表示仍未审核
        normalQuestion.setReportStatus(1);
        normalQuestion.setReportIllegalReason("无");

        System.out.println("管理员反驳审核的问题为 " + normalQuestion);

        //调用dao
        int update = this.update(normalQuestion);
        //成功
        if (update > 0) {
            System.out.println("disagreedReportQuestionSuccess");
            questionMessage.setResult("审核成功,已刷新当前页面");
            questionMessage.setStatus(1);
            questionMessage.setT(normalQuestion);
        } else {
            questionMessage.setResult("审核失败,未刷新当前页面");
        }
        //返回数据
        return questionMessage;
    }

    /**
     * 显示当前用户还没有经过审核的问题
     *
     * @param userId：
     * @return PageBean<Question>
     */
    public PageBean<Question> showNotPassQuestion(int userId) {
        //过滤数据查找
        List<Question> notPassQuestions = this.selectAll().stream()
                .filter(question -> question.getPublishUserId().equals(userId) && question.getCheckStatus() == 0)
                .collect(Collectors.toList());
        System.out.println("当前用户没有通过审核的问题对象");
        for (Question NotPassQuestion : notPassQuestions) {
            System.out.println(NotPassQuestion);
        }

        //返回数据
        return new PageBean<>(notPassQuestions.size(), notPassQuestions);
    }

    /**
     * 向用户显示他被举报的问题
     *
     * @param userId：
     * @return PageBean<Question>
     * @throws Exception：
     */
    public PageBean<Question> showReportedQuestion(int userId) throws Exception {
        //查找过滤数据
        List<Question> reportedQuestions = this.selectAll()
                .stream()
                .filter(question -> question.getPublishUserId().equals(userId))
                .filter(question -> question.getReportStatus() == 0 || question.getReportStatus() == -1)
                .collect(Collectors.toList());

        System.out.println("当前用户被举报的问题对象 ");

        for (Question reportedQuestion : reportedQuestions) {
            System.out.println(reportedQuestion);
        }
        return new PageBean<>(reportedQuestions.size(), reportedQuestions);
    }

    /**
     * 显示管理员还没有审核的用户上传的问题
     *
     * @return PageBean<Question>
     */
    public PageBean<Question> listUncheckedQuestions() {
        // 封装返回对象
        PageBean<Question> questionPageBean = new PageBean<>(0, null);

        //查询
        List<Question> uncheckedQuestions = this.selectAll().stream().
                filter(question -> question.getCheckStatus() == 0 && "审核中".equals(question.getCheckIllegalReason())).
                collect(Collectors.toList());

        //初始化
        if (!uncheckedQuestions.isEmpty()) {
            questionPageBean.setRows(uncheckedQuestions);
            questionPageBean.setTotalCount(uncheckedQuestions.size());
        }
        //返回数据
        return questionPageBean;
    }

    /**
     * 向管理员显示所有被举报的问题
     *
     * @return PageBean<Question>
     */
    public PageBean<Question> listReportedQuestions() {
        // 封装返回对象
        PageBean<Question> questionPageBean = new PageBean<>(0, null);

        //查询
        List<Question> reportedQuestions = this.selectAll().stream().
                filter(question -> question.getReportStatus() == 0).
                collect(Collectors.toList());

        //初始化
        if (!reportedQuestions.isEmpty()) {
            questionPageBean.setRows(reportedQuestions);
            questionPageBean.setTotalCount(reportedQuestions.size());
        }
        //返回数据
        return questionPageBean;
    }

    /**
     * 按标题搜索我感兴趣的问题
     *
     * @param myInterestedQuestion：
     * @return PageBean<Question>
     */
    public PageBean<Question> searchQuestion(String myInterestedQuestion) {
        PageBean<Question> questionPageBean = new PageBean<>(0, null);
        //校验搜索框的输入是否符合要求
        if ((!IfValidInputUtil.ifValidValue(myInterestedQuestion)) || (!IfValidInputUtil.emptyCheckPass(myInterestedQuestion))) {
            return questionPageBean;
        }
        //调用dao
        List<Question> questions = QuestionDao.getInstance()
                .findAll(" where title like '%" + myInterestedQuestion + "%'");
        //判断
        if (!questions.isEmpty()) {
            questionPageBean.setRows(questions);
            questionPageBean.setTotalCount(questions.size());
        }
        //返回数据
        return questionPageBean;
    }


}
